package com.tutor.lzm.function.teacher.act;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.tutor.lzm.AppSession;
import com.tutor.lzm.R;
import com.tutor.lzm.activity.BaseActivity;
import com.tutor.lzm.bean.SubjectBean;
import com.tutor.lzm.bean.TeacherDetailInfo;
import com.tutor.lzm.bean.TeacherExperienceBean;
import com.tutor.lzm.http.BaseResponse;
import com.tutor.lzm.http.HttpClient;
import com.tutor.lzm.http.request.GetAllSubjectRequest;
import com.tutor.lzm.http.request.SaveTeacherInforRequest;
import com.tutor.lzm.http.request.TeacherDetailInfoRequest;
import com.tutor.lzm.utils.ProjectStringUtils;
import com.tutor.syslib.Logs;
import com.tutor.syslib.impl.OneChoiceImpl;
import com.tutor.syslib.util.MessageTools;
import com.tutor.syslib.util.TextUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zzgpc on 2017-9-24.
 * 我是老师
 */
public class IamTeacherAct extends BaseActivity {

    @BindView(R.id.img_fill_in_information)
    ImageView imgFillInInformation;
    @BindView(R.id.tv_degree_of_completion)
    TextView tvDegreeOfCompletion;
    @BindView(R.id.tv_personal_profile_status)
    TextView tvPersonalProfileStatus;
    @BindView(R.id.rl_personal_profile)
    RelativeLayout rlPersonalProfile;
    @BindView(R.id.tv_teacher_experience_num)
    TextView tvTeacherExperienceNum;
    @BindView(R.id.rl_teacher_experience)
    RelativeLayout rlTeacherExperience;
    @BindView(R.id.tv_teacher_feature)
    TextView tvTeacherFeature;
    @BindView(R.id.rl_teacher_feature)
    RelativeLayout rlTeacherFeature;
    @BindView(R.id.tv_teach_grader)
    TextView tvTeachGrader;
    @BindView(R.id.rl_teach_grader)
    RelativeLayout rlTeachGrader;

    @BindView(R.id.tv_my_sex)
    TextView tvMySex;
    @BindView(R.id.rl_my_sex)
    RelativeLayout rlMySex;

    @BindView(R.id.tv_teach_subject)
    TextView tvTeachSubject;
    @BindView(R.id.rl_teach_subject)
    RelativeLayout rlTeachSubject;
    @BindView(R.id.et_teach_price)
    EditText etTeachPrice;
    @BindView(R.id.et_work_age)
    EditText etWorkAge;
    /**
     * 保存老师数据
     */
    private SaveTeacherInforRequest request = new SaveTeacherInforRequest();
    private TeacherDetailInfo info;
    private List<SubjectBean> subjectList;

    public static void start(Context context) {
        Intent intent = new Intent(context, IamTeacherAct.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.act_iam_teacher);
        ButterKnife.bind(this);
        initTitle("我是老师", "保存", rightClick);
        Picasso.with(this)
                .load(R.mipmap.fill_in_information)
                .into(imgFillInInformation);
        initData();

        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private View.OnClickListener rightClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveTeacherInfo();
        }
    };

    /**
     * 教师资料保存
     */
    private void saveTeacherInfo() {

        String price = etTeachPrice.getText().toString().trim();
        if (TextUtil.isNull(price)) {
            MessageTools.showToast(oThis, "请输入授课时薪");
            return;
        }
        request.price = price;
        String workAge = etWorkAge.getText().toString().trim();
        if (TextUtil.isNull(price)) {
            MessageTools.showToast(oThis, "请输入教龄");
            return;
        }
        request.workAge = workAge;
        if (request.sex == -1) {
            MessageTools.showToast(getApplicationContext(), "请选择性别");
            return;
        }
        if (request.categoryType == -1) {
            MessageTools.showToast(getApplicationContext(), "请选择授课年级");
            return;
        }
        if (TextUtil.isEmail(request.categoryId)) {
            MessageTools.showToast(getApplicationContext(), "请选择授课科目");
            return;
        }

        request.userId = AppSession.getInstance().getUserId();

        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(oThis, "保存成功");
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
            }
        });

    }


    private void initView() {


        List<TeacherExperienceBean> seniorityList = info.seniorityList;
        if (seniorityList != null && seniorityList.size() > 0) {
            tvTeacherExperienceNum.setText("共" + seniorityList.size() + "条");
        }
        if (info.price != 0) {
            etTeachPrice.setText(info.price + "");
        }

        if (info.workingAge != 0) {
            etWorkAge.setText(info.workingAge + "");
        }

        if (TextUtil.isNull(info.characteristic)) {
            tvTeacherFeature.setText("请选择");
        } else {
            tvTeacherFeature.setText("已完善");
        }


        tvTeachSubject.setText(info.categoryIdText);
        tvTeachGrader.setText(info.categoryTypeText);
        tvMySex.setText(ProjectStringUtils.getSex(info.sex));

        request.categoryType = info.categorytype;
        request.categoryId = info.categoryId;
        request.sex = info.sex;
    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        if (!EventBus.getDefault().isRegistered(this))
//            EventBus.getDefault().register(this);
//    }
//
//
//    @Override
//    public void onStop() {
//        super.onStop();
//        EventBus.getDefault().unregister(this);
//    }


    private void initData() {
        final TeacherDetailInfoRequest request = new TeacherDetailInfoRequest();
        request.setTeacherId(AppSession.getInstance().getUserId());
        request.setUserId(AppSession.getInstance().getUserId());
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                info = (TeacherDetailInfo) response;
                if (info == null) {
                    return;
                }
                initView();
                return;

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.d(tag, "getRecommendSubject    code" + code + "      msg=" + msg);
            }
        });
        getAllSubject();
    }

    @OnClick({R.id.rl_personal_profile, R.id.rl_teacher_experience, R.id.rl_teacher_feature,
            R.id.rl_teach_grader, R.id.rl_teach_subject, R.id.rl_my_sex})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_personal_profile:
                break;
            case R.id.rl_teacher_experience:
                TeacherExperienceListAct.start(this, null);
                break;
            case R.id.rl_teacher_feature:
                if (info == null) {
                    MessageTools.showToast(this, "数据加载失败，重新加载");
                    initData();
                    return;
                }
                AddCharacterAct.start(this, info.characteristic);
                break;
            case R.id.rl_my_sex:
                //我的性别
                selectSex();
                break;
            case R.id.rl_teach_grader:
                selectGrader();
                break;
            case R.id.rl_teach_subject:
                selectSubject();
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventMessage(List<TeacherExperienceBean> beanList) {
        Logs.v(tag, "eventMessage   times");
        if (beanList != null && beanList.size() > 0) {
            tvTeacherExperienceNum.setText("共" + beanList.size() + "条");
        }

    }

    /**
     * 选择性别
     */
    private void selectSex() {
        String[] types = getResources().getStringArray(R.array.sex);
        MessageTools.showOneChoiceDialog(this, "请选择性别", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvMySex.setText(text);
                request.sex = (position + 1);
            }
        });
    }


    /**
     * 选择年级
     */
    private void selectGrader() {
        String[] types = getResources().getStringArray(R.array.grader_text);
        MessageTools.showOneChoiceDialog(this, "请选择年级", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvTeachGrader.setText(text);
                request.categoryType = position + 1;
            }
        });
    }

    /**
     * 选择科目
     */
    private void selectSubject() {
        int size = subjectList.size();
        String[] types = new String[size];
        for (int i = 0; i < size; i++) {
            types[i] = subjectList.get(i).getCategoryName();
        }
        MessageTools.showOneChoiceDialog(this, "请选择学科", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvTeachSubject.setText(text);
                request.categoryId = subjectList.get(position).getCategoryId();
            }
        });
    }

    /**
     * 获取所有学科
     */
    private void getAllSubject() {
        GetAllSubjectRequest request = new GetAllSubjectRequest();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                try {
                    subjectList = (List<SubjectBean>) response;
                    Logs.e(tag, "subjectList大小为 " + subjectList.size());
                } catch (Exception e) {
                    Logs.e(tag, "onSuccess   getAllSubject接口错误， e=" + e);
                }

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.e(tag, "onFailListener    getAllSubject接口错误， msg=" + msg);
            }
        });
    }

}
